import Vue from 'vue'
import Vuex from 'vuex'
import {request} from '@/common/js/request'
import { getUserInfo ,getOrderCount, getCategoryList,getRecommended} from '@/common/js/api'
import dayjs from 'dayjs';
Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		openExamine: false,//是否开启审核状态
		token: '',
		userInfo: {},
		timerIdent: false,//全局1s定时器，只在全局开启一个，所有需要定时执行的任务监听该值即可，无需额外开启
		cartCount: 0, //购物车数量
		orderCount: {}, //订单数量
		categoryList: [], //课程分类信息
		courseList:[],
		recommendedList:[]
	},
	getters: {
		hasLogin(state){
			return !!state.token;
		}
	},
	mutations: {
		//更新state数据
		setStateAttr(state, param){
			if(param instanceof Array){
				for(let item of param){
					state[item.key] = item.val;
				}
			}else{
				state[param.key] = param.val;
			}
		},
		//更新token
		setToken(state, data){
			const {token,user} = data;
			state.token = token;
			uni.setStorageSync('uniIdToken', token);
			this.dispatch('getUserInfo'); //更新用户信息
			this.dispatch('getOrderCount'); //更新订单数量
			
		},
		//退出登录
		logout(state){
			state.token = '';
			uni.removeStorageSync('uniIdToken');

			setTimeout(()=>{
				state.userInfo = {};
			}, 1100)
		},
	},
	actions: {

		//更新用户信息
		async getUserInfo({state, commit}){
			const res = await getUserInfo();
			if(res.code === 200){
				const userInfo = res.data[0];
				if(userInfo.birthday) userInfo.birthday = dayjs(userInfo.birthday).format('YYYY-MM-DD')
				commit('setStateAttr', {
					key: 'userInfo',
					val: userInfo
				})
			}else{
				this.commit('logout');
			}
		},
		//更新推荐课程列表
		async getRecommendedList({state, commit}){
			let data = [];
			try {
				const res = await getRecommended();
				data = res.data;
				
			}catch (err){
				console.error('更新推荐课程列表 => ', err);
			}
			commit('setStateAttr', {
				key: 'recommendedList',
				val: data
			})
		},
		//更新用户订单数量
		async getOrderCount({state, commit}){
			let data = []
			if(state.token){
				try {
					const res = await getOrderCount();
					data = res.data;
				}catch (err){
					console.error('更新用户订单数量 => ', err);
				}
			}
			commit('setStateAttr', {
				key: 'orderCount',
				val: data
			})
		},
		//更新商品分类
		async getCategory({state, commit}){
			let data = []
			try {
				const res = await getCategoryList();
				data = res.data;
			}catch (err){
				console.error('更新更新商品分类数组 => ', err);
			}
			commit('setStateAttr', {
				key: 'categoryList',
				val: data
			})
		},
	}
}) 


export default store
